package cn.hxzy.icon.icon.service.impl;


import cn.hxzy.icon.icon.entity.Icon;
import cn.hxzy.icon.icon.entity.vo.PageBean;
import cn.hxzy.icon.icon.repository.IconRepository;
import cn.hxzy.icon.icon.service.IconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 实现
 *
 * @author little black
 */
@Service("IconService")
public class IconServiceImpl implements IconService {
    @Autowired
    private IconRepository iconRepository;

    /**
     * 查询全部信息
     * @param pageBean
     * @return
     */
    @Override
    public PageBean<Icon> findAll(PageBean<Icon> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.asc("id")));
        Page<Icon> all = iconRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return pageBean;
    }

    /**
     * 模糊查询
     * @param pageBean
     * @param name
     * @return
     */
    @Override
    public PageBean<Icon> findByNameLike(PageBean<Icon> pageBean,String name) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.asc("id")));
        String s = "%" + name + "%";
        Page<Icon> byNameLike = iconRepository.findByNameLike(s,pageable);
        pageBean.setList(byNameLike.getContent());
        pageBean.setCount(byNameLike.getTotalElements());
        pageBean.setPageCount(byNameLike.getTotalPages());
        return pageBean;
    }

    /**
     * 添加
     * @param icon
     */
    @Override
    public void add(Icon icon) {
        iconRepository.save(icon);
    }

    /**
     * id查找
     * @param id
     * @return
     */
    @Override
    public Icon FindById(Integer id) {
        Optional<Icon> byId = iconRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    /**
     * 修改
     * @param icon
     */
    @Override
    public void update(Icon icon) {
        iconRepository.save(icon);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        iconRepository.deleteById(id);
    }
}
